<template>
<div 
    class="like-bt" 
    @click="onLike">
    <i 
        :class="getMyLikeState(dataInfo.id,type)?'el-icon-star-on':'el-icon-star-off'">
    </i>
    {{localNumber}}
</div>
</template>

<script>
//like按钮组件
export default {
    props:{
        number:{ //like的数量
            type:Number,
            default:0,
        },
        type:{  //like的数据类型
            type:String, 
            default:'',
        },
        dataInfo:{  //like的对象详细数据
            type:Object, 
            default:()=>{
                return {};
            },
        },
    },
    data(){
        return{
            localNumber:0,
        };
    },
    watch:{
        number: {
            handler() {
                this.localNumber = this.number;
            },
            immediate: true,
        }
    },
    methods:{
        getMyLikeState(id,type){
            return this.$store.getters.getMyLikeState({id,type});
        },
        onLike(){
            this.$store.commit('addMyLike',{
                type:this.type,
                data:this.dataInfo,
            }); //写入我的like
            let data = this.$store.state.addLike[this.type];
            if(this.dataInfo.id && !data[this.dataInfo.id]){
                this.addLike();
            }
        },
        addLike(){
            if(!this.dataInfo.id) return;
            this.loading = true;
            let q;
            switch(this.type){
                case 'color':
                    q = this.$Api.addColorLike({
                        id:this.dataInfo.id,
                    });
                    break;
                case 'gradient':
                    q = this.$Api.addGradientLike({
                        id:this.dataInfo.id,
                    });
                    break;
                case 'shadow':
                    q = this.$Api.addShadowLike({
                        id:this.dataInfo.id,
                    });
                    break;
            }
            q.then(()=>{
                this.localNumber++;
                this.$store.commit('addLikeRecord',{
                    type:this.type,
                    id:this.dataInfo.id,
                });
            }).catch(({msg}) =>{
                this.$message.error(msg);
            }).finally(()=>{
                this.loading = false;
            });
        },
    },
}
</script>
<style lang="scss" scoped>
.like-bt{
    color: #3a3a59;
    border-radius: 4px;
    transition: all .1s;
    box-sizing: border-box;
    text-align: center;
    background-color: #fff;
    line-height: 1.3rem;
    cursor: pointer;
    border: 1px solid #e9f2f9;
    font-size: 1.3rem;
    padding: 8px 10px;
    font-weight: bold;
    transition: all 0.2s;
    &:hover{
        background-color: #f5fcff;
    }
    i{
        font-weight: bold;
    }
}
</style>

